import { getAttrInfoListApi } from '@/api/AttrApi'
import { getEditSpuImageListApi, getEditSpuSaleAttrListApi } from '@/api/SPUApi'

const getDefaultState = () => {
  return {
    AddSpuListData: {
      category3Id: 0,
      description: '',
      id: 0,
      spuImageList: [],
      spuName: '',
      spuSaleAttrList: [],
      tmId: ''
    }
  }
}

export default {
  namespaced: true,
  state: {
    AddSpuListData: {
      category3Id: 0,
      description: '',
      id: 0,
      spuImageList: [],
      spuName: '',
      spuSaleAttrList: [],
      tmId: ''
    },
    spuImageList: [],
    // 销售属性
    spuSaleAttrList: [],
    // 平台属性
    attrInfoList: []
  },
  mutations: {
    UPDATE_BASESTATE(state, obj) {
      state.AddSpuListData = {
        ...obj
      }
    },
    RESER_STORE(state) {
      Object.assign(state, getDefaultState())
    },
    ADD_SKUSLIT(state, obj) {
      state.spuImageList = obj.spuImageList
      state.spuSaleAttrList = obj.spuSaleAttrList
      state.attrInfoList = obj.attrInfoList
    }
  },
  actions: {
    async updateBaseState({ commit }, obj) {
      const imgData = await getEditSpuImageListApi(obj.id)
      const AttrData = await getEditSpuSaleAttrListApi(obj.id)
      AttrData.data.forEach((item) => {
        item.isShowEdit = true
      })
      imgData.data.forEach((key) => {
        key.name = key.imgName
        key.url = key.imgUrl
      })
      obj.spuImageList = imgData.data
      obj.spuSaleAttrList = AttrData.data
      commit('UPDATE_BASESTATE', obj)
    },
    async addSkuList({ state, commit }, id) {
      const imgData = await getEditSpuImageListApi(id)
      const AttrData = await getEditSpuSaleAttrListApi(id)
      const AttrInfoListData = await getAttrInfoListApi(
        this.state.sortStore.Category1Id,
        this.state.sortStore.Category2Id,
        this.state.sortStore.Category3Id
      )
      commit('ADD_SKUSLIT', {
        spuImageList: imgData.data,
        spuSaleAttrList: AttrData.data,
        attrInfoList: AttrInfoListData.data
      })
    },
    resetState({ commit }) {
      commit('RESER_STORE')
    }
  }
}
